<?php
declare(strict_types=1);

namespace Zms\Mime;

class Mime
{
    private static $mime;


    /**
     * 获取文件后缀对应的类型
     * @return mixed
     */
    public static function getMimeData()
    {
        if (is_array(self::$mime)) {
            return self::$mime;
        }
        $data = file_get_contents(dirname(__DIR__) . '/asset/mime.json');
        self::$mime = json_decode($data, true);
        return self::$mime;
    }


    /**
     * 获取文件类型
     * @param string $extention 文件后缀
     * @return string
     */
    public static function getMime(string $extention): string
    {
        $extention = trim(strtolower($extention));
        $all = self::getMimeData();
        return $all[$extention] ?? '';
    }

    /**
     * 获取文件类型
     * @param array $extentions 需要的文件后缀集合
     * @return array
     */
    public static function getMimes(array $extentions): array
    {
        $mimes = [];
        foreach ($extentions as $extention) {
            $mimes[] = self::getMime($extention);
        }
        return $mimes;
    }

    /**
     * 获取文件类型后缀
     * 传入文件类型，获取所包含的文件格式
     * @param string $mime 文件类型
     * @return array
     */
    public static function getExtention(string $mime): array
    {
        $mime = trim(strtolower($mime));
        $extentions = [];
        foreach (self::getMimeData() as $extention => $mimename) {
            if ($mimename === $mime) {
                $extentions[] = $extention;
            }
        }
        return $extentions;
    }
}